package com.example.a10928.weifriend.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a10928.weifriend.App;
import com.example.a10928.weifriend.R;
import com.example.a10928.weifriend.http.api.VariableName;
import com.example.a10928.weifriend.ui.home.HomeFragment;
import com.example.a10928.weifriend.ui.personal_center.PersonalCenterFragment;
import com.example.a10928.weifriend.ui.rank_list.FindFragment;
import com.example.a10928.weifriend.ui.rank_list.RankListFragment;
import com.example.a10928.weifriend.ui.task_center.TaskCenterFragment;
import com.example.a10928.weifriend.ui.task_center.TaskRecordActivity;
import com.example.a10928.weifriend.util.HProgressDialogUtils;
import com.example.a10928.weifriend.util.L;
import com.example.a10928.weifriend.util.RxUtil;
import com.example.a10928.weifriend.util.StatusBarUtil;
import com.example.a10928.weifriend.util.UpdateAppHttpUtil;
import com.example.a10928.weifriend.util.VersionUtil;
import com.example.a10928.weifriend.view.BottomButtonLayout;
import com.mylhyl.circledialog.CircleDialog;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.service.DownloadService;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.List;
import java.util.Objects;

import me.leefeng.promptlibrary.PromptDialog;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    BottomButtonLayout home_page,task_center,rank_list,personal_center;
    RelativeLayout rl;

    private Fragment[] fmList = new Fragment[4];
    private String[] fmTag = new String[4];
    private int index = 0;
    PromptDialog dialog;

    @Override
    public int getContentView() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {

        dialog=new PromptDialog(this);
        fmList[0]=new HomeFragment();
        fmList[1]=new TaskCenterFragment();
//        fmList[2]=new RankListFragment();
        fmList[2]=new FindFragment();
        fmList[3]=new PersonalCenterFragment();

        fmTag[0]="homepage";
        fmTag[1]="taskcenter";
        fmTag[2]="ranklist";
        fmTag[3]="personalcenter";


        StatusBarUtil.setStatusColor(getWindow(),ContextCompat.getColor(this, R.color.main),1f);


    }

    @Override
    public void initView() {
        if(Objects.requireNonNull(getSupportActionBar()).isShowing()){
            getSupportActionBar().hide();
        }

        home_page=(BottomButtonLayout)findViewById(R.id.home_page);
        task_center=(BottomButtonLayout)findViewById(R.id.task_center);
        rank_list=(BottomButtonLayout)findViewById(R.id.rank_list);
        personal_center=(BottomButtonLayout)findViewById(R.id.personal_center);
        rl=(RelativeLayout)findViewById(R.id.rl);

        home_page.setOnClickListener(this);
        task_center.setOnClickListener(this);
        rank_list.setOnClickListener(this);
        personal_center.setOnClickListener(this);

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.add(R.id.rl, fmList[0], fmTag[0]);
        transaction.commit();

        // checkUpdate();

    }

    private void checkUpdate(){
        App.app().getBpService().getAndroid(VersionUtil.getVersionCode(this))
                .compose(RxUtil.io2main())
                .subscribe(
                        r->{
                            if(TextUtils.isEmpty(r.getData().getAndroid_url()) ){
                                return;
                            }
                            String s=r.getData().getAndroid_url();
                            s.replace("\\","");

                            Log.v("zzwzzw","downLoad: "+s);

                            new CircleDialog.Builder()
                                    .setCanceledOnTouchOutside(false)
                                    .setCancelable(false)
                                    .setTitle("app更新")
                                    .setText("升级")
                                    .configText(params -> {
//                                params.gravity = Gravity.LEFT | Gravity.TOP;
                                        params.gravity=Gravity.CENTER;
                                        //  params.padding = new int[]{100, 0, 100, 50};
                                    })
                                    .setNegative("关闭应用", v->{

                                        finish();
                                    })
                                    .setPositive("确定", v ->{
                                        L.v("download",s);
                                        downLoad(s);
/*                            new AppUpdater.Builder()
                                .setChannelId("1")
                                .setChannelName("app更新")
                                .serUrl(s)
                                .setFilename("AppUpdater.apk")
                                .build(MainActivity.this)
                                .start();*/
                                    })
                                    .show(getSupportFragmentManager());
                        },
                        RxUtil::errorException
                );

    }

    @Override
    public void onClick(View v) {

        int now=0;
        switch (v.getId()){
            case R.id.home_page:

                now=0;
                break;

            case R.id.task_center:

                now=1;
//                View view = setTitleText(ThemeEnum.Menu_No_Back, "任务中心", "历史纪录");
//                 view.findViewById(R.id.actionbar_title_menu).setOnClickListener(v1 ->{
//                    startActivity(new Intent(this,TaskRecordActivity.class));
//                });

                break;

            case R.id.rank_list:

                //setTitleText(ThemeEnum.Default,"排行榜");
                now=2;
                break;

            case R.id.personal_center:
          
                //setTitleText(ThemeEnum.Default,"个人中心");
                now=3;
                break;
        }
        L.v("zzw",""+now);
        if(index!=now){
            switchFragment(index,now);
            select(index,now);

            index=now;
        }
    }

    public void switchFragment (int one, int two) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();


        Fragment fm_one = fm.findFragmentByTag(fmTag[one]);
        if (fm_one != null) {
            transaction.hide(fm_one);
        }
        Fragment fm_two = fm.findFragmentByTag(fmTag[two]);
        if (fm_two != null) {
            transaction.show(fm_two);
        } else  {
            transaction.add(R.id.rl, fmList[two], fmTag[two]);
        }
        transaction.commit();

    }

    public void select(int old,int news){
        switch(old){
            case 0:

                home_page.setIv(R.drawable.home_page_unselect);
                break;
            case 1:

                task_center.setIv(R.drawable.task_center);
                break;
            case 2:

                rank_list.setIv(R.drawable.rank_list);
                break;
            case 3:

                personal_center.setIv(R.drawable.personal_center);
                break;
        }

        switch(news){
            case 0:

                home_page.setIv(R.drawable.home_page);
                break;
            case 1:

                task_center.setIv(R.drawable.task_center_select);
                break;
            case 2:

                rank_list.setIv(R.drawable.rank_list_select);
                break;
            case 3:

                personal_center.setIv(R.drawable.personal_center_select);
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        App.activity=this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.activity=null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        AndPermission.with(this)
                .requestCode(VariableName.REQUEST_PERMISSION)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .callback(permissionListener)
                .rationale(new RationaleListener(){
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(MainActivity.this, rationale).show();
                    }
                })
                .start();



    }

    PermissionListener permissionListener=new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {



        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            Toast.makeText(MainActivity.this,"权限申请失败",Toast.LENGTH_SHORT).show();
            if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, deniedPermissions)) {
                AndPermission.defaultSettingDialog(MainActivity.this, VariableName.REQUEST_SETTING)
                        .setTitle("权限申请")
                        .setMessage("需要此权限")
                        .setPositiveButton("好")
                        .setNegativeButton("否", null)
                        .show();

            }
        }
    };

    public void showProgress(){
        dialog.dismiss();
        dialog.showLoading("加载中");
    }

    public void dismmProgress(){
        dialog.dismiss();
    }

    private void downLoad(String s){
        UpdateAppBean updateAppBean = new UpdateAppBean();

        //设置 apk 的下载地址
        updateAppBean.setApkFileUrl(s);

        String path = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {
            try {
                path = getExternalCacheDir().getAbsolutePath();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(path)) {
                path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
            }
        } else {
            path = getCacheDir().getAbsolutePath();
        }

        //设置apk 的保存路径
        updateAppBean.setTargetPath(path);
        //实现网络接口，只实现下载就可以
        updateAppBean.setHttpManager(new UpdateAppHttpUtil());

        UpdateAppManager.download(this, updateAppBean, new DownloadService.DownloadCallback() {
            @Override
            public void onStart() {
                HProgressDialogUtils.showHorizontalProgressDialog(MainActivity.this, "下载进度", false);
            }

            @Override
            public void onProgress(float progress, long totalSize) {
                HProgressDialogUtils.setProgress(Math.round(progress * 100));

            }

            @Override
            public void setMax(long totalSize) {
            }

            @Override
            public boolean onFinish(File file) {
                HProgressDialogUtils.cancel();

                return true;
            }

            @Override
            public void onError(String msg) {
                HProgressDialogUtils.cancel();
            }

            @Override
            public boolean onInstallAppAndAppOnForeground(File file) {
                return false;
            }
        });
    }


}
